package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;
import com.gsk.europepharma.salesReport.utils.UtilsSalesReport;

/**
 * Gestion des donnees pour le graphe en bulles.
 */
public class DataBubble extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Variables de session
		HttpSession sessionObject = request.getSession();
		Integer cs_adm_pdt = (Integer) sessionObject.getAttribute("cs_adm_pdt");
		Integer cs_adm_rgpt = (Integer) sessionObject.getAttribute("cs_adm_rgpt");
		if (request.getParameter("product") != null) {
			cs_adm_rgpt = Integer.parseInt(request.getParameter("product"));
		}
		Integer cs_adm_prstn = (Integer) sessionObject.getAttribute("cs_adm_prstn");
		Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
		Integer cs_month = (Integer) sessionObject.getAttribute("cs_month");
		// Fin de session 
		
		String idGeog = request.getParameter("idGeog");
		Integer idGeogInteger = Integer.parseInt(idGeog);
		
		String geog = request.getParameter("geog"); 
		String nivGeog = request.getParameter("nivGeog"); 
		
		String source = request.getParameter("source");
		Integer CS_SRC = Integer.parseInt(source);
		String unite = request.getParameter("unite");
		String periode = request.getParameter("periode");
		String quota = request.getParameter("quota"); 
		
		String indicateur1 = request.getParameter("indicateur1");
		String indicateur2 = request.getParameter("indicateur2");
		
		tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
		Session session = salesDAO.getSession();
		
		Query req;
		String strReq = "";
		strReq = salesDAO.QUERY_GRAPH_BUBBLE;
		req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
		
		req.setParameter("data", unite + periode);
		
		req.setInteger("cs_adm_pdt", cs_adm_pdt);
		req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
		req.setInteger("cs_adm_prstn", cs_adm_prstn);
		req.setInteger("CS_SRC", CS_SRC);
		req.setInteger("cs_network", cs_network);
		req.setInteger("cs_month", cs_month);
		req.setInteger("idGeog", idGeogInteger);
		req.setString("nivGeog", nivGeog);		
		
		Double firstValueIndicateur = 0.0;

		String fillColorGreen  = ",marker: {fillColor: {radialGradient: { cx: 0.4, cy: 0.3, r: 0.7 },stops: [ [0, 'rgba(0,255,0,0.2)']   , [1, 'rgba(0,255,0,0.9)']   ]}}";
		String fillColorRed    = ",marker: {fillColor: {radialGradient: { cx: 0.4, cy: 0.3, r: 0.7 },stops: [ [0, 'rgba(255,0,0,0.2)']   , [1, 'rgba(255,0,0,0.9)']   ]}}";
		String fillColorOrange = ",marker: {fillColor: {radialGradient: { cx: 0.4, cy: 0.3, r: 0.7 },stops: [ [0, 'rgba(255,157,0,0.2)'] , [1, 'rgba(255,157,0,0.9)'] ]}}";

		ArrayList result = new ArrayList(req.list());
		Iterator iter = result.iterator();
		HashMap hm = new HashMap();
		ArrayList data = new ArrayList();
		while (iter.hasNext()) {
			Object[] val = (Object[]) iter.next();
			
			Double indicateurValue1 = UtilsSalesReport.getIndicateur(
										indicateur1, 
										Double.parseDouble(val[3].toString()), 
										Double.parseDouble(val[4].toString()), 
										Double.parseDouble(val[5].toString()), 
										Double.parseDouble(val[6].toString()), 
										1);
			
			Double indicateurValue2 = UtilsSalesReport.getIndicateur(
										indicateur2, 
										Double.parseDouble(val[3].toString()), 
										Double.parseDouble(val[4].toString()), 
										Double.parseDouble(val[5].toString()), 
										Double.parseDouble(val[6].toString()), 
										1);
			
			// Double marche = UtilsSalesReport.getMarche(Double.parseDouble(val[5].toString()), 2);
			Double valueQuota = 0.0;
			if (valueQuota.equals("QP")) {
				valueQuota = Double.parseDouble(val[8].toString());
			} else if (quota.equals("QM")) {
				valueQuota = Double.parseDouble(val[9].toString());
			}
			
			if (geog.equals(val[0].toString())) {
				hm.put("xPere", indicateurValue1);
				hm.put("yPere", indicateurValue2);
				firstValueIndicateur = indicateurValue1;
			} else {
				String tmp = "{x:";
				Double d = indicateurValue1;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", y:");
				d = indicateurValue2;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", z:");
				d = valueQuota; //marche;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", lib:'");
				tmp = tmp.concat(val[0].toString() + "'");
				
				tmp = tmp.concat(", idGeog:" + Integer.parseInt(val[1].toString()) + ", niveau:'" + val[2].toString() + "'");
				
				// Couleurs des bulles
				if (indicateurValue2 >= 0) {
					tmp = tmp.concat(fillColorGreen);
				} else if (firstValueIndicateur <= indicateurValue1) {
					tmp = tmp.concat(fillColorOrange);
				} else {
					tmp = tmp.concat(fillColorRed);
				}
				
				tmp = tmp.concat("}");
				data.add(tmp);
			}
		}
		
		// Recuperation des donnees de l UGA
		if (nivGeog.equals("Secteur") || nivGeog.equals("UGA")) {
			strReq = salesDAO.QUERY_GRAPH_BUBBLE_U_G_A;
			req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
			
			req.setParameter("data", unite + periode);
			
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_network", cs_network);
			req.setInteger("cs_month", cs_month);
			req.setInteger("idGeog", idGeogInteger);
			req.setString("nivGeog", nivGeog);		

			result = new ArrayList(req.list());
			iter = result.iterator();
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
				
				Double indicateurValue1 = UtilsSalesReport.getIndicateur(
											indicateur1, 
											Double.parseDouble(val[3].toString()), 
											Double.parseDouble(val[4].toString()), 
											Double.parseDouble(val[5].toString()), 
											Double.parseDouble(val[6].toString()), 
											1);
				
				Double indicateurValue2 = UtilsSalesReport.getIndicateur(
											indicateur2, 
											Double.parseDouble(val[3].toString()), 
											Double.parseDouble(val[4].toString()), 
											Double.parseDouble(val[5].toString()), 
											Double.parseDouble(val[6].toString()), 
											1);

				// Double marche = UtilsSalesReport.getMarche(Double.parseDouble(val[5].toString()), 2);
				Double valueQuota = 0.0;
				if (valueQuota.equals("QP")) {
					valueQuota = Double.parseDouble(val[8].toString());
				} else if (quota.equals("QM")) {
					valueQuota = Double.parseDouble(val[9].toString());
				}
				
				if (geog.equals(val[0].toString())) {
					hm.put("xPere", indicateurValue1);
					hm.put("yPere", indicateurValue2);	
					firstValueIndicateur = indicateurValue1;
				} else {
					String tmp = "{x:";
					Double d = indicateurValue1;
					tmp = tmp.concat(d.toString());
					tmp = tmp.concat(", y:");
					d = indicateurValue2;
					tmp = tmp.concat(d.toString());
					tmp = tmp.concat(", z:");
					d = valueQuota; //marche;
					tmp = tmp.concat(d.toString());
					tmp = tmp.concat(", lib:'");
					tmp = tmp.concat(val[0].toString() + "'");
					
					String niveauTmp = "UGA";
					
					tmp = tmp.concat(", idGeog:" + Integer.parseInt(val[1].toString()) + ", niveau:'" + niveauTmp + "'");
					
					// Couleurs des bulles 
					if (indicateurValue2 >= 0) {
						tmp = tmp.concat(fillColorGreen);
					} else if (firstValueIndicateur <= indicateurValue1) {
						tmp = tmp.concat(fillColorOrange);
					} else {
						tmp = tmp.concat(fillColorRed);
					}
					
					tmp = tmp.concat("}");
					data.add(tmp);
				}
			}	
		}
			
		
		// Recuperation des donnees UGP
		if (nivGeog.equals("UGA")) {
			strReq = salesDAO.QUERY_GRAPH_BUBBLE_UGP;
			req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
			
			req.setParameter("data", unite + periode);
			
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_network", cs_network);
			req.setInteger("idGeog", idGeogInteger);
			result = new ArrayList(req.list());
			iter = result.iterator();
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();

				// A l'UGP, on force les 2 indicateurs : PM et DeltaPM 
				Double deltapm = Double.parseDouble(val[4].toString());
				Double pm = Double.parseDouble(val[3].toString());
				Double rang = Double.parseDouble(val[5].toString());
				
				String tmp = "{x:";
				Double d = pm;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", y:");
				d = deltapm;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", z:");
				d = rang;
				tmp = tmp.concat(d.toString());
				tmp = tmp.concat(", lib:'");
				tmp = tmp.concat(val[0].toString() + "'");
				
				String niveauTmp = "UGP";
				
				tmp = tmp.concat(", idGeog:" + Integer.parseInt(val[1].toString()) + ", niveau:'" + niveauTmp + "'");
				
				// Couleurs des bulles 
				if (deltapm >= 0) {
					tmp = tmp.concat(fillColorGreen);
				} else if (firstValueIndicateur <= pm) {
					tmp = tmp.concat(fillColorOrange);
				} else {
					tmp = tmp.concat(fillColorRed);
				}
				
				tmp = tmp.concat("}");
				data.add(tmp);
			}
		} 

		hm.put("data", data);

		JSONObject json = JSONObject.fromObject(hm);

		response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();

		return null;
	}
}
